# Contributor: Natanael Copa <ncopa@alpinelinux.org>
# Maintainer: Sertonix <sertonix@posteo.net>
pkgname=apk-tools3
pkgver=3.0.0_pre2_git20240401
_commit=b7a7ea728e242a04f32f8e56ddc3d8d85960ee28
pkgrel=0
pkgdesc="Alpine Package Keeper v3 - package manager for alpine"
arch="all"
url="https://git.alpinelinux.org/apk-tools"
license="GPL-2.0-only"
subpackages="$pkgname-dbg $pkgname-dev $pkgname-static $pkgname-doc $pkgname-libs"
# Musl 1.2 introduced new ABI for time64 => upgrading apk-tools
# while staying on musl <1.2 causes missing symbols
# starting with musl 1.2.3_git (pre 1.2.3), we added DT_RELR
# it is possible for old systems to upgrade, and apk-tools would upgrade first,
# which would upgrade to a binary that cannot run until musl is upgraded.
# forcing this constraint makes apk upgrade musl as part of the 'critical' transaction,
# and update musl first.
depends="musl>=1.2.3_git20230424"
_lua="5.3"
makedepends_build="openssl>3 lua$_lua lua$_lua-lzlib scdoc"
makedepends_host="meson zlib-dev zstd-dev openssl-dev zlib-static zstd-static openssl-libs-static linux-headers"
makedepends="$makedepends_build $makedepends_host"
_d_lua=disabled
if [ "$CBUILD" = "$CHOST" ]; then
	_d_lua=enabled
	subpackages="$subpackages lua$_lua-apk3:luaapk"
	makedepends="$makedepends lua$_lua-dev"

	# ca-certificates-bundle needed for https certificate validation
	depends="$depends ca-certificates-bundle"
fi
source="$pkgname-$pkgver.tar.gz::https://gitlab.alpinelinux.org/alpine/apk-tools/-/archive/$_commit/apk-tools-$_commit.tar.gz"
builddir=$srcdir/apk-tools-$_commit

build() {
	abuild-meson \
		--bindir=/sbin \
		--libdir=/lib \
		-Dlua_version=$_lua -Dlua=$_d_lua \
		-Ddocs=enabled \
		-Dhelp=enabled \
		-Dstatic_apk=true \
		. output
	VERSION=$pkgver-r$pkgrel meson compile -C output
}

check() {
	meson test --no-rebuild --print-errorlogs -C output
}

package() {
	DESTDIR="$pkgdir" meson install --no-rebuild -C output
	install -d "$pkgdir"/lib/apk/db \
		"$pkgdir"/lib/apk/exec \
		"$pkgdir"/etc/apk/keys \
		"$pkgdir"/etc/apk/protected_paths.d
}

static() {
	pkgdesc="$pkgdesc (static binary)"
	depends=""

	amove sbin/apk.static
	${CROSS_COMPILE}strip "$subpkgdir"/sbin/apk.static
	local pubkey="${PACKAGER_PUBKEY:-$PACKAGER_PRIVKEY.pub}"
	openssl dgst -sha1 -sign "$PACKAGER_PRIVKEY" \
		-out "$subpkgdir"/sbin/apk.static.SIGN.RSA."${pubkey##*/}" \
		"$subpkgdir"/sbin/apk.static
}

libs() {
	pkgdesc="$pkgdesc (libraries)"
	amove 'lib/libapk*'
}

luaapk() {
	pkgdesc="Lua module for $pkgname"
	depends=""
	amove 'usr/lib/lua*'
}

sha512sums="
b7889bd50192e83ab051ab9bf2cebf80a0c22029b8a60b9329e426ac0e394dc856a4ecb5648c32cc3eb72d6b0cf09a8395b54c53d48fb5ab4645d0f8bdaa69cd  apk-tools3-3.0.0_pre2_git20240401.tar.gz
"
